package com.xbjtech.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.xbjtech.model.Region;
import com.xbjtech.redis.RedisUtils;
import com.xbjtech.service.RegionService;

import tk.mybatis.mapper.entity.Example;

@RestController
@RequestMapping("/region")
public class RegionController {
	
	@Autowired
	RegionService regionService;
	
	@Autowired
	RedisUtils redisUtils;
	
	@GetMapping("/getRegionByParId")
	public String getRegionByParId(
			@RequestParam(value = "parId", required = true)
			Integer parId) {
		// 建议一定做缓存
		String key = "region_" + parId;
		byte[] bs = redisUtils.get(key.getBytes());
		String json = null;
		if (null == bs) {
			// 从数据库里查出来，并且将查询出的结果放到redis里面
			synchronized (this) {
				byte[] bytes = redisUtils.get(key.getBytes());
				if (null == bytes) {
					Example ex = new Example(Region.class);
					ex.createCriteria().andEqualTo("parId", parId);
					List<Region> regions = regionService.selectByExample(ex);
					json = JSON.toJSONString(regions);
					redisUtils.set(key.getBytes(), json.getBytes(), 24 * 60 * 60);
				} else {
					json = new String(bytes);
				}
				return json;
			}
		} else {
			return new String(bs);
		}
	}
	
	@RequestMapping("/json")
	public String getRegions() {
		// 做缓存
		String key = "llaz-allRegions";
		String json = null;
		byte[] bs = redisUtils.get(key.getBytes());
		System.out.println(bs);
		if (null == bs) {
			synchronized (this) {
				byte[] bytes = redisUtils.get(key.getBytes());
				if (bytes == null) {
					List<Map<String, Object>> regions = regionService.selectAllRegions();
					Map<String, Object> newMap = new HashMap<>();
					for (Map<String, Object> map : regions) {
						Object mkey = map.get("id");
						Object value = map.get("district");
						newMap.put(mkey.toString(), value);
					}
					String jsonString = JSON.toJSONString(newMap);
					json = jsonString;
					redisUtils.set(key.getBytes(), jsonString.getBytes(), 24 * 60 * 60);
				} else {
					json = new String(bs);
				}
			}
		} else {
			json = new String(bs);
		}
		return json;
	}
}
